/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rie06.openvoip.client.IHM.communication;

import com.rie06.openvoip.client.Contact;
import com.rie06.openvoip.client.Conversation;
import com.rie06.openvoip.client.IHM.home.InterfaceClient;
import com.rie06.openvoip.client.IHM.home.PanelContact;
import com.rie06.openvoip.client.IHM.home.PanelRequestConversation;
import com.rie06.openvoip.client.IHM.home.WindowNewContact;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.UUID;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

/**
 *
 * @author Sylvain
 */
public class CommunicationController implements ActionListener, MouseListener {

    private WindowDialog dialogWindow;
    private InterfaceClient interfaceClient;
    private WindowListAddContactConversation windowListAddContactConversation;
    private WindowNewContact windowNewContact;
    private static final Logger logger = Logger.getLogger(CommunicationController.class);

    public CommunicationController() {
    }

    public void actionPerformed(ActionEvent e) {
        String source = e.getActionCommand();

        // PanelAddContact
        if ("addContact".equals(source)) {
            interfaceClient.getAddContact().addContact();
            //WindowNewContact newContactWindow =  new WindowNewContact(this.interfaceClient, this);
        }


        // PanelContact
        if ("buttonStartConversation".equals(source)) {
            startConversation(e);
        }

        if ("buttonDeleteContactToList".equals(source)) {
            logger.log(Level.INFO, "Delete Contact to ListContact ");
            deleteContactToListContact(e);
        }


        // PanelOption 
        if ("buttonAddContactDialog".equals(source)) {
            System.out.println("** J'ajoute un contact à la conversation **");
            WindowListAddContactConversation windowListAddContactConversation = new WindowListAddContactConversation(this, dialogWindow);
        }

        // PanelOption
        if ("buttonCloseDialog".equals(source)) {
            closeAllConversation(e);
        }


        // PanelOption
        if ("buttonPauseAllDialog".equals(source)) {
            logger.log(Level.INFO, " Make pause to all contacts ");
            pauseAllConversation(e);
        }

        // PanelOption
        if ("buttonCallConversation".equals(source)) {
            logger.log(Level.INFO, " Start call conversation");
            callAllConversation(e);
        }


        // PanelMessage
        if ("sendMessage".equals(source)) {
            logger.log(Level.INFO, " Send message ");

            JButton buttonMessage = (JButton) e.getSource();
            PanelMessage panelMessage = (PanelMessage) buttonMessage.getParent();

            String textClient = interfaceClient.getServer().getServerConfig().getUserName() + " : " + panelMessage.getZoneText().getText() + "\n";
            String textToSend = panelMessage.getZoneConversation().getText() + textClient;

            panelMessage.getZoneText().setText("");

            panelMessage.getConversation().sendMessage(textClient);

            panelMessage.getZoneConversation().setText(textToSend);
            panelMessage.getZoneConversation().repaint();
            panelMessage.getZoneConversation().validate();

        }

        // PanelListContactToAddConversation
        if ("buttonAddContactConversation".equals(source)) {
            logger.log(Level.INFO, " Add contact to conversation ");
            addContactToListConversation(e);
        }

        // PanelContactConversation
        if ("muteButton".equals(source)) {
            logger.log(Level.INFO, " mute contact");
            muteContact(e);

        }

        // PanelContactConversation
        if ("soundButton".equals(source)) {
            logger.log(Level.INFO, "sound contact");
            soundContact(e);
        }


        // PanelContactConversation
        if ("deleteButton".equals(source)) {
            System.out.println("** Je veux supprimer un contact **");
            deleteContactToListConversation(e);
        }

        //PanelRequestConversation
        if ("acceptContactToConversation".equals(source)) {

            JButton buttonAccept = (JButton) e.getSource();
            PanelRequestConversation panelRequestConversation = (PanelRequestConversation) buttonAccept.getParent();

            String description = panelRequestConversation.getContact().getName();

            logger.log(Level.DEBUG, "acceptContactToConversation: conversation uuid: " + panelRequestConversation.getConversation().getUuid().toString());

            if (interfaceClient.getConversationWindowList().containsKey(panelRequestConversation.getConversation().getUuid())) {
                WindowDialog windowDialog = (WindowDialog) interfaceClient.getConversationWindowList().get(panelRequestConversation.getConversation().getUuid());
                windowDialog.setVisible(true);
                windowDialog.getPanelDialog().update();
            } else {
                logger.log(Level.DEBUG, "acceptContactToConversation: conversation doesn't exist in list!");
            }
        }

    }

    //************************ METHODES **************************//
    /**
     * Supprimer un contact de la liste de conversation
     *
     */
    public void deleteContactToListConversation(ActionEvent e) {

        JButton buttonDelete = (JButton) e.getSource();
        PanelContactConversation panelContactConversation = (PanelContactConversation) buttonDelete.getParent();

        panelContactConversation.getConversation().removeContactFromConversation(panelContactConversation.getContact());

        panelContactConversation.setVisible(false);
        dialogWindow.getPanelDialog().repaint();
        dialogWindow.getPanelDialog().revalidate();
    }

    /**
     * Ajoute un contact à la liste de conversation
     *
     */
    public void addContactToListConversation(ActionEvent e) {

        JButton buttonAddContactConversation = (JButton) e.getSource();
        PanelAddListContactConversationExtended panelAddListContactConversationExtended = (PanelAddListContactConversationExtended) buttonAddContactConversation.getParent();

        Contact contact = panelAddListContactConversationExtended.getContact();

        windowListAddContactConversation.getWindowDialog().getConversation().addContact(contact);
        windowListAddContactConversation.getWindowDialog().getPanelDialog().update();
        windowListAddContactConversation.setVisible(false);
    }

    /**
     * Démarre une conversation
     *
     */
    public void startConversation(ActionEvent e) {

        JButton buttonStart = (JButton) e.getSource();
        PanelContact panelContact = (PanelContact) buttonStart.getParent();
        String description = panelContact.getContact().getName();

        Conversation conversation = interfaceClient.getClient().createConversation(panelContact.getContact());

        WindowDialog windowDialog = new WindowDialog(this, conversation, true);

        windowDialog.getPanelDialog().update();
    }

    /**
     * Ferme la fenêtre de dialogue et la conversation avec tout les autres
     * contacts
     *
     */
    public void closeAllConversation(ActionEvent e) {

        JOptionPane windowConfirm = new JOptionPane();
        int retour = windowConfirm.showConfirmDialog(dialogWindow, "Attention !! cette fermeture entraînera l'arrêt de tous les appels \n Voulez-vous continuer ? ", "Avertissement", windowConfirm.YES_NO_OPTION);
        System.out.println("valeur de retour de la jDialog : " + retour);

        if (retour == 0) {
            JButton buttonClose = (JButton) e.getSource();
            PanelOption panelOption = (PanelOption) buttonClose.getParent();
            logger.log(Level.DEBUG, " WARNING !! window is just invisble !! ou pas ");

            panelOption.getDialogWindow().getConversation().closeConversation();
            interfaceClient.getConversationWindowList().remove(panelOption.getDialogWindow().getConversation().getUuid());

            WindowDialog wd = panelOption.getDialogWindow();
            wd = null;
        }
    }

    /**
     * Lance un appel audio avec tout les contacts présent dans la fenêtre de
     * dialogue
     *
     */
    public void callAllConversation(ActionEvent e) {

        JButton buttonCall = (JButton) e.getSource();
        PanelOption panelOption = (PanelOption) buttonCall.getParent();

        Conversation conversation = panelOption.getDialogWindow().getConversation();
        if (conversation.getClient().getCurrentConversation() == null || conversation.getClient().getCurrentConversation().equals(conversation.getUuid())) {
            conversation.play();

            panelOption.getButtonPauseAllConversation().setEnabled(true);
            buttonCall.setEnabled(false);

            panelOption.repaint();
            panelOption.revalidate();
        } else {
            JOptionPane.showMessageDialog(null, "Veuillez mettre en pause la conversation en cours pour activer celle-ci.", "", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    /**
     * Met en pause tout les contacts de la fenêtre de conversation
     */
    public void pauseAllConversation(ActionEvent e) {

//        if (retour == 0) {
        JButton buttonClose = (JButton) e.getSource();
        PanelOption panelOption = (PanelOption) buttonClose.getParent();

        Conversation conversation = panelOption.getDialogWindow().getConversation();

        if (conversation.getClient().getCurrentConversation() == null || conversation.getClient().getCurrentConversation().equals(conversation.getUuid())) {
            conversation.pause();

            panelOption.getButtonCallConversation().setEnabled(true);
            buttonClose.setEnabled(false);
        }


    }

    /**
     * Coupe le son d'un contact
     */
    public void muteContact(ActionEvent e) {
        JButton buttonMute = (JButton) e.getSource();
        PanelContactConversation panelContactConversation = (PanelContactConversation) buttonMute.getParent();

        panelContactConversation.getSoundContactButton().setVisible(true);
        buttonMute.setVisible(false);


        panelContactConversation.repaint();
        panelContactConversation.revalidate();
    }

    /**
     * Permet d'entendre la voix d'un contact
     */
    public void soundContact(ActionEvent e) {
        JButton buttonSound = (JButton) e.getSource();
        PanelContactConversation panelContactConversation = (PanelContactConversation) buttonSound.getParent();

        panelContactConversation.getMuteContactButton().setVisible(true);
        buttonSound.setVisible(false);

        panelContactConversation.repaint();
        panelContactConversation.revalidate();
    }

    /**
     * Supprime un contact de la liste de conversation
     */
    public void deleteContactToListContact(ActionEvent e) {
        JButton buttonDelete = (JButton) e.getSource();
        PanelContact panelContact = (PanelContact) buttonDelete.getParent();
        String description = panelContact.getContact().getUuid().toString().substring(0, 10);

        UUID contactUuid = panelContact.getContact().getUuid();
        this.getInterfaceClient().getClient().getContactList().remove(contactUuid);
    }

    //**************  MOUSE LISTENER *******************//
    public void mouseClicked(MouseEvent e) {
    }

    public void mousePressed(MouseEvent e) {
    }

    public void mouseReleased(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {

        PanelContact panelContact = (PanelContact) e.getSource();
        //panelContact.setBackground(new Color(189, 189, 189));
        panelContact.setBackground(new Color(51, 204, 255));
    }

    public void mouseExited(MouseEvent e) {
        PanelContact panelContact = (PanelContact) e.getSource();
        panelContact.setBackground(null);
    }

    //**************  GETTEURS SETTEURS *******************//
    public InterfaceClient getInterfaceClient() {
        return interfaceClient;
    }

    public WindowDialog getDialogWindow() {
        return dialogWindow;
    }

    public void setDialogWindow(WindowDialog dialogWindow) {
        this.dialogWindow = dialogWindow;
    }

    public WindowListAddContactConversation getWindowListAddContactConversation() {
        return windowListAddContactConversation;
    }

    public void setWindowListAddContactConversation(WindowListAddContactConversation windowListAddContactConversation) {
        this.windowListAddContactConversation = windowListAddContactConversation;
    }

    public WindowNewContact getWindowNewContact() {
        return windowNewContact;
    }

    public void setWindowNewContact(WindowNewContact windowNewContact) {
        this.windowNewContact = windowNewContact;
    }

    public void setInterfaceClient(InterfaceClient interfaceClient) {
        this.interfaceClient = interfaceClient;
    }
}
